package com.itheima.config;


import com.google.common.collect.Sets;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Configuration//配置类
@Slf4j
public class TaskConfig {
    @Component
    public class CleanupTask {

        @Autowired
        private RedisTemplate<String, String> redisTemplate;

        @Autowired
        private AliOssUtil aliOssUtil;


        @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行
        public void cleanupGarbageImages() {
            try {
                // 获取 all_uploaded_pics 和 valid_setmeal_pics 集合
                Set<String> allUploadedPics = redisTemplate.opsForSet().members("all_uploaded_pics");
                Set<String> validSetmealPics = redisTemplate.opsForSet().members("valid_setmeal_pics");

                // 计算差值，得到垃圾图片名称
                Set<String> garbageImages = Sets.difference(allUploadedPics, validSetmealPics);
                log.info("垃圾图片名称: {}", garbageImages);
                //截取保存在redis文件名后40位
                garbageImages = garbageImages.stream().map(imageName -> imageName.substring(imageName.length() - 40)).collect(java.util.stream.Collectors.toSet());

                // 删除阿里云 OSS 中的垃圾图片
                deleteGarbageImagesFromOSS(garbageImages);

                // 从 Redis 中移除垃圾图片名称
                if (!garbageImages.isEmpty()) {
                    redisTemplate.opsForSet().remove("all_uploaded_pics", garbageImages.toArray());
                }

                log.info("垃圾图片清理完成，共清理 {} 张图片", garbageImages.size());
            } catch (Exception e) {
                log.error("垃圾图片清理失败", e);
            }
        }

        private void deleteGarbageImagesFromOSS(Set<String> garbageImages) {
            for (String imageName : garbageImages) {
                aliOssUtil.delete(imageName);
            }
        }
    }
}
